<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div class="c_666 fw">组织管理</div>
        <div class="flex">
          <span class="m_right20">
            剩余
            <span
              :style="{
                color: store.state.organization_days < 10 ? '#EE5656' : '',
              }"
              >{{ store.state.organization_days }}</span
            >
            天</span
          >
          <el-button
            type="primary"
            @click="
              ;(show_box = true),
                (add_form_data.organizationAdministratorId = '')
            "
            >新增</el-button
          >

          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        style="text-align: center"
        :data="list"
        row-key="id"
        :max-height="max_height"
        border
        highlight-current-row
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="组织名称"
          prop="name"
          v-if="header_list[0].showTable"
          key="组织名称"
        ></el-table-column>
        <!-- <el-table-column
          label="上级组织"
          v-if="header_list[1].showTable"
          key="组织名称"
          ><template #default="scope:any">
            <div v-if="scope.row.parentOrganization">
              {{ scope.row.parentOrganization.name }}
            </div>
          </template></el-table-column
        > -->
        <el-table-column
          label="状态"
          v-if="header_list[1].showTable"
          key="状态"
        >
          <template #default="scope: any">
            <div v-if="scope.row.status" style="color: #3580eb">已启用</div>
            <div v-else>已停用</div>
          </template>
        </el-table-column>
        <el-table-column
          label="组织管理员"
          v-if="header_list[2].showTable"
          key="组织管理员"
        >
          <template #default="scope: any">
            <div>{{ scope.row.organizationAdministrator?.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="备注" v-if="header_list[3].showTable" key="备注"
          ><template #default="scope: any"
            ><div class="text_over">
              <el-tooltip :content="scope.row.remark" placement="bottom">
                {{ scope.row.remark }}
              </el-tooltip>
            </div></template
          ></el-table-column
        >
        <el-table-column label="操作" width="124px">
          <template #default="scope: any">
            <table_edit
              :role="has_role_list"
              @edit_item="update_list(scope)"
              @delete_item="delete_list({ item: scope.row, type: 0 })"
            ></table_edit>
            <!-- <el-button @click="update_list(scope)">编辑</el-button>
            <el-button @click="delete_list(scope)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <el-drawer
    v-model="show_box"
    direction="rtl"
    @close="resetForm(addorganizationform)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增组织</h4>
      <h4 v-else>编辑组织</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        label-width="100px"
        :rules="rules"
        ref="addorganizationform"
      >
        <el-form-item label="组织名称" prop="name">
          <el-input
            v-model="add_form_data.name"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="组织管理员" prop="organizationAdministratorId">
          <el-select v-model="add_form_data.organizationAdministratorId">
            <el-option
              v-for="item in user_list"
              :key="item.id"
              :value="item.id"
              :label="item.name"
              :disabled="item.isAdmin"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="add_form_data.status" :label="true">启用</el-radio>
          <el-radio v-model="add_form_data.status" :label="false"
            >停用</el-radio
          >
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            resize="none"
            v-model="add_form_data.remark"
            placeholder="请输入"
            show-word-limit
            maxlength="300"
          ></el-input>
        </el-form-item>
        <div class="m_top10 tr">
          <el-button @click="resetForm(addorganizationform)">取消</el-button>
          <el-button
            type="primary"
            :loading="btn_loading"
            @click="submit(addorganizationform)"
            >保存</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
  <dialog_box
    @submit_delete="submit_delete"
    @close="show_delete_box = false"
    :delete_name="delete_name"
    :show_delete_box="show_delete_box"
  ></dialog_box>
</template>

<script lang="ts" setup>
import { check_role, formatDate } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import dialog_box from '@/view/components/dialog_box.vue'
import table_edit from '@/view/components/table_edit.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, nextTick } from 'vue'
import { FormInstance, ElMessage } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { useStore } from 'vuex'
import { getCookie } from '@/utils/cookie'
const store = useStore()
const has_role_list = ref([
  { path: '', has_role: true },
  { path: 'organization/put', has_role: true },
  { path: 'organization/delete', has_role: true },
  { path: 'organization/post', has_role: true },
])
// type FormInstance = InstanceType<typeof ElForm>
const addorganizationform = ref<FormInstance>()
const rules = ref({
  name: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
  organizationAdministratorId: [
    { required: true, message: '请选择组织管理员', trigger: 'change' },
  ],
})
const user_info = JSON.parse(getCookie('user_info'))
const list = ref()
const loading = ref(false)
const btn_loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref([
  {
    label: '组织名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  //   {
  //     label: '上级组织',
  //     value: '',
  //     showTable: true,
  //     type: 'input',
  //     isShow: true,
  //     options: [],
  //   },
  {
    label: '状态',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '组织管理员',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
  {
    label: '备注',
    value: '',
    showTable: true,
    type: 'input',
    isShow: false,
    options: [],
  },
])
const page_data = ref({
  current: 1,
  pageSize: 10,
  status: '',
  name: '',
  //   parentId: '',
  remark: '',
  organizationAdministratorId: '',
})
const add_form_data = ref({
  id: '',
  status: true,
  name: '',
  organizationAdministratorId: '',
  //   parentId: '',
  remark: '',
})
onMounted(() => {
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_list()
  get_user_list()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const user_list = ref([])
const get_user_list = () => {
  axios
    .request({
      url: serviceApi.user_list,
      method: 'post',
      data: {
        current: 1,
        pageSize: 10000,
        enterpriseId:
          store.state.enterprise_id != '' // 当前登录企业 vuex > cookie
            ? store.state.enterprise_id
            : getCookie('enterprise_id'),
      },
    })
    .then((res) => {
      console.log(res)
      user_list.value = res.data.content
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const show_delete_box = ref()
const delete_name = ref()
const delete_id = ref()
const submit_delete = () => {
  axios
    .request({
      url: serviceApi.organization_crud + '/' + delete_id.value,
      method: 'delete',
    })
    .then((res) => {
      ElMessage.success('操作成功！')
      show_delete_box.value = false
      get_list()
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const delete_list = (e) => {
  console.log(e)
  delete_id.value = e.item.id
  delete_name.value = e.item.name
  show_delete_box.value = true
}
const update_list = (e) => {
  add_form_data.value = {
    id: e.row.id,
    status: e.row.status,
    name: e.row.name,
    organizationAdministratorId: e.row.organizationAdministrator.id,
    // parentId: e.row.parentOrganization ? e.row.parentOrganization.id : '',
    remark: e.row.remark,
  }
  show_box.value = true
}
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) {
        return
      }
      btn_loading.value = true
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.organization_crud
              : serviceApi.organization_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          resetForm(formEl)
          btn_loading.value = false
          show_box.value = false
          get_list()
        })
        .catch((err) => {
          btn_loading.value = false
          ElMessage.error(err)
        })
    }
  })
}
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.organization_list,
      method: 'post',
      data: page_data.value,
    })
    .then((res) => {
      console.log(res)
      list.value = res.data
      loading.value = false
    })
    .catch((err) => {
      loading.value = false
      ElMessage.error(err)
    })
}
const max_height = ref()
nextTick(() => {
  max_height.value = window.innerHeight - 270 // 不带分页的 table 高度
})
const search_key = () => {
  page_data.value = {
    current: 1,
    pageSize: 10,
    status: header_list.value[1].value,
    name: header_list.value[0].value,
    // parentId: header_list.value[2].value,
    remark: header_list.value[3].value,
    organizationAdministratorId: header_list.value[2].value,
  }
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    name: '',
    status: true,
    remark: '',
    // parentId: '',
    organizationAdministratorId: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped></style>
